package com.mumu.quratz.controller;

import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.*;

/**
 * @author mumu
 * @version 1.0
 * @date 2023/12/12 17:40
 * @describe
 */
@Slf4j
@RestController
@RequestMapping("req")
public class ReqController {

    static ThreadPoolExecutor threadPoolExecutor;

    static {
        threadPoolExecutor = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors(),
                Runtime.getRuntime().availableProcessors() * 2,
                60L,
                TimeUnit.SECONDS,
                //选用无界的阻塞队列 则设置的mumPoolSize参数没有意义
                new LinkedBlockingDeque<Runnable>(1000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );
    }

    @GetMapping("test")
    public void req() throws SchedulerException, InterruptedException {
        final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes re = (ServletRequestAttributes) requestAttributes;
        re.getRequest().setAttribute("name", "wss");

        CompletableFuture
                .runAsync(() -> {
                    log.info("线程一到达");
                    // RequestContextHolder.setRequestAttributes(requestAttributes);
                }, threadPoolExecutor)
                .thenRun(() -> {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    log.info("线程二到达");
                    ServletRequestAttributes req = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                    HttpServletRequest request = req.getRequest();
                    System.out.println("---" + request.getAttribute("name"));
                    System.out.println("---" + request.getAttribute("name"));
                });

        log.info("主线程到达");
        //Thread.sleep(5000);

        threadPoolExecutor.shutdown();
    }
}
